import express from 'express';
import Alidns20150109, * as $Alidns20150109 from '@alicloud/alidns20150109';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import Util, * as $Util from '@alicloud/tea-util';
import schedule from 'node-schedule';

const server = express();
server.use(express.json());
server.use(express.urlencoded({extended: false}));

let tempIp: string | undefined = undefined
server.get("/", (req, res) => {
    if (tempIp === undefined) {
        res.status(500).send("Get Records Fail, See Container Logs.");
    } else {
        res.send(tempIp)
    }
})

server.listen(16602, () => {
    console.log("Server is Running At Port 16602");
});

const accessKeyId = process.env.ACCESS_KEY_ID;
const accessKeySecret = process.env.ACCESS_KEY_SECRET;
const domain = process.env.ALIDNS_DOMAIN;
const interval = process.env.INTERVAL;
console.log(`${new Date().toLocaleString()} Setting: accessKeyId: ${accessKeyId} accessKeySecret: ${accessKeySecret} domain: ${domain} interval: ${interval}`);
//每隔多少分钟运行一次
schedule.scheduleJob(`0 */${interval} * * * *`, async () => {
    getRecords(accessKeyId!!, accessKeySecret!!, domain!!).then((data) => {
        console.log(`${new Date().toLocaleString()}  Get IP Record Success:${data}`);
        tempIp = data as string
    }).catch((err) => {
        console.log(`${new Date().toLocaleString()}  Get IP Record Fail:${err}`);
        tempIp = undefined;
    })
})


async function getRecords(accessKeyId: string, accessKeySecret: string, domain: string) {
    return new Promise((resolve, reject) => {
        try {
            let config = new $OpenApi.Config({
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                accessKeyId: accessKeyId,
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                accessKeySecret: accessKeySecret,
            });
            // Endpoint 请参考 https://api.aliyun.com/product/Alidns
            config.endpoint = `alidns.cn-hangzhou.aliyuncs.com`;
            const client = new Alidns20150109(config);
            let describeDomainRecordsRequest = new $Alidns20150109.DescribeDomainRecordsRequest({
                domainName: domain,
            });
            client.describeDomainRecordsWithOptions(describeDomainRecordsRequest, new $Util.RuntimeOptions({})).then(res => {
                let records = res.body?.domainRecords?.record
                if (records === undefined) {
                    reject("No Records Found");
                } else {
                    let found = false
                    for (const record of records) {
                        if (record.domainName == domain) {
                            found = true
                            resolve(record.value)
                        }
                    }
                    if (!found) {
                        reject("No Records Found");
                    }
                }
            }).catch((err) => {
                reject(err.message)
            });
        } catch (e) {
            reject(e.message)
        }
    })
}